<?php

namespace app\api\controller;

use think\Db;

class Cook
{
//    连接现场数据库
    public function __construct()
    {
        $db = [
            'type' => 'mysql',
            'dsn' => '',
            'hostname' => 'jmxx.chinaboling.cn',
            'database' => 'cook',
            'username' => 'root',
            'password' => 'chuanxu123$',
            'charset' => 'utf8',
            'prefix' => 't_',
        ];
        config('database', $db);
    }

    public function index()
    {
        $openid = input('openid');
        $code = input('code');
        file_put_contents('/tmp/cook.txt', $openid . "\t" . $code . "\n", 8);
        if (!cache('token')) {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxa1d89617c92c2c96&secret=9f6f624ac3ca1e883a24f46a8aeaec64";
            $contents = file_get_contents($url);
            $contents = json_decode($contents, true);
            cache('token', $contents['access_token'], 30);
        }

        $access_token = cache('token');
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" . $access_token;
        $body = json_encode(['code' => $code]);
        $info = $this->post_curls($url, $body);
        file_put_contents('/tmp/cook.txt', $info . "\n", 8);
        file_put_contents('/tmp/cook.txt', str_repeat('-', 21) . "\n", 8);
        $info_decode = json_decode($info, true);
        if (isset($info_decode['phone_info']['phoneNumber'])) {
            $pn = $info_decode['phone_info']['phoneNumber'];
            $user = Db::table('t_user')->where('phone', $pn)->find();
            if (!$user) {
                $output = [
                    'result' => 0,
                    'msg' => '您的手机号尚未注册',
                ];
            } else {
                if ($user['openid'] != $openid) {
                    // 修改2个表的openid
                    Db::query('SET FOREIGN_KEY_CHECKS=0;');
                    Db::table('t_user')->where('phone', $pn)->setField('openid', $openid);
                    $is_exist = Db::table('t_wxuser')->where('openid', $openid)->count();
                    if (!$is_exist) {
                        Db::table('t_wxuser')->where('openid', $user['openid'])->setField('openid', $openid);
                    }
                    Db::table('t_user_bak')->insert(['phone' => $pn, 'old_openid' => $user['openid'], 'new_openid' => $openid]);
                    Db::query('SET FOREIGN_KEY_CHECKS=1;');
                    $output = [
                        'result' => 1,
                        'msg' => '数据已同步，请重新登录',
                    ];
                } else {
                    $output = [
                        'result' => 1,
                        'msg' => '数据同步成功',
                    ];
                }
            }

        } else {
            $output = [
                'result' => 0,
                'msg' => '无法获取手机号码',
            ];
        }
        echo json_encode($output);

    }


    public function holiday()
    {
        $apikey = '9bcf4f100875704de919d53107d2542f9671';
        for ($i = 202401; $i < 202413; $i++) {
            $url = "https://api.apihubs.cn/holiday/get?field=date,weekend,workday,holiday_overtime,holiday_recess&year=2024&month=$i&cn=1&size=31&api_key=$apikey";
            $content = file_get_contents($url);
            $contents = json_decode($content, true);
            $list = array_reverse($contents['data']['list']);
            foreach ($list as $v) {
                $date = $v['date'];
                $type = 0;//默认工作日

                if ($v['holiday_overtime'] > 10) $type = 2;//调休
                if ($v['weekend'] == 1 && $v['workday'] <> 1) $type = 3;//周末并且非工作日
                if ($v['holiday_recess'] == 1) $type = 1;//法定节假日

                Db::table('t_holiday')->insert(['ddatetime' => $date, 'type' => $type, 'type_bak' => $type]);

            }
        }


    }

    private function post_curls($url, $post)
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $res; // 返回数据，json格式

    }

//    订餐开关
    public function cook0()
    {
        $openid = input('openid');
        $_ddatetime = input('ddatetime');
        $ddatetime = date('Y-m-d H:i:s', strtotime($_ddatetime));
        $name = Db::table('t_user')->where('openid', $openid)->value('name');

        $row = Db::table('t_holiday')->where('ddatetime', $ddatetime)->find();

        $log = [
            'username' => $name,
            'ip' => $_SERVER['REMOTE_ADDR'],
            'logtime' => date('Y-m-d H:i:s')
        ];
        if ($row['type'] == $row['type_bak']) {
            if ($row['type'] == 1) {
                Db::table('t_holiday')->where('ddatetime', $ddatetime)->setField('type', 0);
                $log['content'] = "开通{$_ddatetime}的订餐";
            } else {
                Db::table('t_holiday')->where('ddatetime', $ddatetime)->setField('type', 1);
                $log['content'] = "关闭{$_ddatetime}的订餐";
            }
        } else {
            Db::table('t_holiday')->where('ddatetime', $ddatetime)->setField('type', $row['type_bak']);
            $log['content'] = "恢复{$_ddatetime}的订餐";
        }

        Db::table('t_log')->insert($log);
        $output = [
            'result' => 1,
            'msg' => '操作成功',
        ];

        echo json_encode($output);

    }

    public function copy()
    {
        $openid = input('openid');
        file_put_contents(APP_PATH.'cook_openid.txt',date('Y-m-d H:i:s')."\t".$openid."\n",8);
        $activeId = config('site.activity');
        $relationId = '2794015487';
        $tpwd = get_activity_info($activeId, $relationId);
        $output = [
            'result' => 0,
            'msg' => date('Y-m-d H:i:s') . $tpwd,
        ];
        echo json_encode($output);

    }
}